import axios from "axios";
import {useRouter} from "vue-router";
import {useStore} from "vuex"
import {getToken} from "@/plugins/cookie";

axios.defaults.baseURL = 'http://127.0.0.1:8000/'

let config = {}
const _axios = axios.create(config)
const router = useRouter()
const store = useStore()
//请求拦截器
_axios.interceptors.request.use(
    function (config) {
        const token = getToken();
        if(token){
            config.headers["token"] = token
        }
        return config;
    }
)
//响应拦截器,浏览器上有token,但是token已经失效
_axios.interceptors.response.use(
    function (response) {
        if (response.data.code === 1000) {
            store.commit("logout")
            router.replace({name: "Login"})
            return Promise.reject()
        }
        return response;
    },
    function (error) {
        //请求失败
        if (error.response.status === 401) {
            store.commit("logout")
            router.replace({name: "Login"})
        }
        return Promise.reject(error);
    }
)
export default _axios;